package vno.fux.res.pool
{
	import flash.display.Bitmap;
	import flash.utils.Dictionary;
	
	import vno.fux.BaseDisplayObject;
	import vno.fux.res.manager.LoadState;
	import vno.fux.res.manager.ResourceManager;

	public class MapResource extends Resource
	{
		use namespace RM_MRM;
		RM_MRM var _thumbMap:AutoBitmap;
		RM_MRM var _mapTileMatrix:Vector.<Vector.<MapTile>>;
		private var _tileNumX:uint;
		private var _tileNumY:uint;
		
		public function MapResource(id_:uint, setting_:XML)
		{
			super(id_);
			_tileNumX = setting_.tiles.@numX;
			_tileNumY = setting_.tiles.@numY;
		}
		
		override public function create():void
		{
			this._loadStateDic = new Dictionary(true);
			initThumbMap();
			initMapTiles();
		}
		
		private function initThumbMap():void
		{
			_thumbMap = new AutoBitmap;
			this._loadStateDic[_thumbMap] = LoadState.NOT_LOAD;
		}
		
		private function initMapTiles():void
		{
			_mapTileMatrix = new Vector.<Vector.<MapTile>>(_tileNumX, true);
			
			for(var l:int = 0; l<_tileNumX; l++)
			{
				_mapTileMatrix[l] = new Vector.<MapTile>(_tileNumY, true);
			}
			
			for(var i:int = 0; i<_tileNumX; i++)
			{
				for(var j:int = 0; j<_tileNumY; j++)
				{
					var mt:MapTile = new MapTile();
					_mapTileMatrix[i][j] = mt;
					this._loadStateDic[mt] = LoadState.NOT_LOAD;
				}
			}
		}
		
		override public function destroy():void
		{
			destroyThumbMap();
			destroyMapTiles();
			this._loadStateDic = null;
		}
		
		private function destroyThumbMap():void
		{
			_thumbMap.detachAll();
			_thumbMap.dispose();
			_thumbMap = null;
		}
		
		private function destroyMapTiles():void
		{
			for each(var vector:Vector.<MapTile> in _mapTileMatrix)
			{
				for each(var tmp:MapTile in vector)
				{
					tmp.bitmapData.dispose();
				}
			}
			_mapTileMatrix = null;
		}
	
		public function get thumbMap():AutoBitmap
		{
			if(_loadStateDic[_thumbMap] == LoadState.NOT_LOAD)
			{
				_loadStateDic[_thumbMap] = LoadState.PRE_LOAD;
				ResourceManager.getInstance().map.loadThumbMap(id);
			}
			return _thumbMap;
		}

		public function mapTile(x:uint, y:uint):MapTile
		{
			var tile:MapTile = _mapTileMatrix[x][y];
			if(_loadStateDic[tile] == LoadState.NOT_LOAD)
			{
				_loadStateDic[tile] = LoadState.PRE_LOAD;
				ResourceManager.getInstance().map.loadMapTile({id:id, x:x, y:y});
			}
			return _mapTileMatrix[x][y];
		}
		
//		public function toString():String
//		{
//			return "MapResource" + _loadStateDic[_thumbMap];
//		}

	}
}